package hit.persistence;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import hit.core.HomeInventoryTracker;

/**
 * Handles persistence for the HIT system.
 * */
public class SerializationHandler {
	
	public static final String PERSISTENCE_FILE = "hit_data.dat";
	
	/**
	 * Saves a HomeInventoryTracker and its associated graph of objects.
	 * @param hit the HomeInventoryTracker to save
	 * @param file the File to save to
	 * */
	public static void saveData(HomeInventoryTracker hit, File file) {
		try {//write the HomeInventoryTracker
			OutputStream outFile = new BufferedOutputStream(new FileOutputStream(file));
			ObjectOutputStream output = new ObjectOutputStream(outFile);
			output.writeObject(hit);
			output.close();
			outFile.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Reconstitutes a saved HomeInventoryTracker from file.
	 * @param file the File to read from
	 * @return the HomeInventoryTracker
	 * */
	public static HomeInventoryTracker loadData(File file) {
		try {
			//first check to see if the file exists
			if (!file.exists())
				return null;
			
			InputStream inFile = new BufferedInputStream(new FileInputStream(file));
			ObjectInputStream input = new ObjectInputStream(inFile);
			HomeInventoryTracker hit = (HomeInventoryTracker) input.readObject();
			input.close();
			inFile.close();
			
			//reset the facades; they weren't serialized
			hit.ResetFacades();
			
			return hit;
		}
		catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} 
		
		//if anything goes wrong, we just return null
		return null;
	}
}
